#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

int grid[12][12];  // 网格
int sgrid[12][12]; // 显示
int w = 32;		   // 图案大小32*32
int Mx = 0;		   // 生成的数量
int ret = 0;
int bug = 0;

void setup()
{
	for (int i = 1; i <= 10; i++) // 0[1~10]11 防止记录周围雷数时越界
		for (int j = 1; j <= 10; j++)
		{
			sgrid[i][j] = 12;
			if (rand() % 5 == 0)
				grid[i][j] = 11; // 雷
			else
				grid[i][j] = 0; // 地板
		}
	Mx = 0, ret = 0;
	for (int i = 1; i <= 10; i++)
		for (int j = 1; j <= 10; j++)
		{
			int n = 0; // 记录周围雷的数量
			if (grid[i][j] == 11)
			{
				Mx++; //  记录雷的数量
				continue;
			}
			if (grid[i + 1][j] == 11)
				n++;
			if (grid[i][j + 1] == 11)
				n++;
			if (grid[i - 1][j] == 11)
				n++;
			if (grid[i][j - 1] == 11)
				n++;
			if (grid[i + 1][j + 1] == 11)
				n++;
			if (grid[i - 1][j + 1] == 11)
				n++;
			if (grid[i - 1][j - 1] == 11)
				n++;
			if (grid[i + 1][j - 1] == 11)
				n++;
			if (n > 0)
				grid[i][j] = n + 1; // 地雷个数+1->对应图片顺序
		}
	ret = Mx;
}

int main()
{
	srand(time(0));
	RenderWindow window(VideoMode(400, 400), "Minesweeper!--YzHCat");
	Texture t;
	Sprite s(t), score(t);
	t.loadFromFile("../images/tiles.jpg");
	
	setup();
	while (window.isOpen())
	{
		Vector2i pos;
		int x, y;

		Event e;
		while (window.pollEvent(e))
		{
			bug = 0;
			if (e.type == Event::Closed)
				window.close();
			if (e.type == Event::KeyReleased)
			{
				if (e.key.code == Keyboard::R)
					setup();
				if (e.key.code == Keyboard::Escape)
					window.close();
			}
			if (e.type == Event::MouseButtonReleased)
			{
				pos = Mouse::getPosition(window);
				x = pos.x / w;
				y = pos.y / w; // 鼠标所在的方格
				if (e.mouseButton.button == Mouse::Left && sgrid[x][y] == 12)
					sgrid[x][y] = grid[x][y]; // 左键砖块时显示地板
				else if (e.mouseButton.button == Mouse::Right)
				{
					if (sgrid[x][y] == 13)
					{
						Mx++;
						sgrid[x][y] = 12; // 小旗还原成砖块
						if (grid[x][y] == 11)
						{
							ret++;
							bug = 1;
						}
					}
					else if (sgrid[x][y] == 12)
					{
						if (Mx > 0)
						{
							Mx--;
							sgrid[x][y] = 13; // 右键砖块时显示小旗
							if (grid[x][y] == 11)
								ret--;
						}
					}
				}
			}
		}

		window.clear(Color::White);
		for (int i = 1; i <= 10; i++)
			for (int j = 1; j <= 10; j++)
			{
				if (sgrid[x][y] == 11 || ret == 0)
					sgrid[i][j] = grid[i][j]; // 如果点到雷
				s.setTextureRect(IntRect(sgrid[i][j] * w, 0, w, w));
				s.setPosition(i * w, j * w);
				window.draw(s);
			}
		// 得分
		int sc[]{Mx / 10, Mx % 10, w, w + w};
		for (int i = 0; i < 2; i++)
		{
			score.setPosition(sc[i + 2], w * 11 + 2);
			score.setTextureRect(IntRect((sc[i] + 1) * w, 0, w, w + 1 + bug));
			window.draw(score);
		}

		window.display();
	}

	return 0;
}
